package com.kaiwu.tc.persistence.builder.xml;

import com.alibaba.druid.pool.DruidDataSource;
import com.kaiwu.tc.persistence.session.Configuration;
import com.kaiwu.tc.persistence.session.Resources;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author Captain
 * @date 2021/1/23
 **/
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder(){
        configuration = new Configuration();
    }

    public Configuration parse(InputStream in) throws Exception {
        Document docment = new SAXReader().read(in);
        Element rootElement = docment.getRootElement();
        List<Element> nodes = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        nodes.forEach(p -> properties.put(p.attributeValue("name"), p.attributeValue("value")));

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getProperty("driverClass"));
        dataSource.setUrl(properties.getProperty("url"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(dataSource);

        List<Element> mapperList = rootElement.selectNodes("//mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Element element : mapperList) {
            String path = element.attributeValue("resource");
            InputStream inputStream = Resources.getResourceAsStream(path);
            xmlMapperBuilder.parse(inputStream);
        }

        return configuration;

    }
}
